使用 XDocReport 将 .docx 文件转换为 .pdf 文件 您所在的位置:网站首页 java 导出pdf乱码 使用 XDocReport 将 .docx 文件转换为 .pdf 文件

使用 XDocReport 将 .docx 文件转换为 .pdf 文件

2023-08-28 12:36| 来源: 网络整理| 查看: 265

docx转换为pdf网上有很多技术解决方案,本文介绍另外一种,如何使用 XDocReport 库在 Java 中将 Word 文件转换为 PDF 文件;

将 XDocReport 转换器 DOCX XWPF 依赖添加到 Java 项目

如果您使用 Gradle 构建项目,请将以下依赖项添加到 build.gradle 文件中。

implementation group: 'fr.opensagres.xdocreport', name: 'fr.opensagres.xdocreport.converter.docx.xwpf', version: '2.0.3'

如果您使用 Maven 构建项目,请将以下依赖项添加到 pom.xml 文件中

···xml

fr.opensagres.xdocreport fr.opensagres.xdocreport.converter.docx.xwpf 2.0.3

···

如何在 Java 中将 .docx 文件转换为 .pdf 文件

在 Java 中,对于给定的 Word 文件,我们可以使用 XDocReport API 通过以下步骤将其转换为 PDF 文件。

第 1 步:使用 FileInputStream 将 .docx 文件作为 InputStream 打开。第 2 步:使用 XWPFDocument(InputStream is) 构造函数创建新的 XWPFDocument 对象。第 3 步:使用 PdfOptions.create() 静态方法创建 PdfOptions 的新实例。第 4 步:使用 FileOutputStream 将 .pdf 文件写入 OutputStream。第 5 步:使用 PdfConverter.getInstance().convert(XWPFDocument document, OutputStream out, T options) 方法将 .docx 文件转换为 .pdf 文件。在下面的 FileConverter Java 类中,我们通过上述步骤实现了一个方法,将 .docx 文件转换为具有给定文件名的 .pdf 文件。

FileConverter.java

import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter; import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.xwpf.usermodel.XWPFDocument; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; public class FileConverter { public void convertWordToPdf(String docxFileName, String pdfFileName) { try(InputStream inputStream = new FileInputStream(docxFileName); OutputStream outputStream = new FileOutputStream(pdfFileName)) { XWPFDocument document = new XWPFDocument(inputStream); PdfOptions options = PdfOptions.create(); // Convert .docx file to .pdf file PdfConverter.getInstance().convert(document, outputStream, options); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ··· # 如何使用 FileConverter 类将 Word 转换为 PDF 文件 例如,我们有一个位于 D:\SimpleSolution\Data\Document.docx 的示例 Word 文件,其内容如下图所示。 ![image.png](https://ucc.alicdn.com/pic/developer-ecology/cf85435d326e45cca5ceb30208881976.png) Java 使用 XDocReport 将 .docx 文件转换为 .pdf 文件 在下面的示例 Java 程序中,我们使用上一步中的 FileConverter 类将上面的示例 Word 文件转换为 PDF 文件。 ConvertDocxToPdfExample1.java 执行 Java 应用程序,我们在 D:\SimpleSolution\Data\Document.pdf 生成 PDF 文件,如下图所示。 ![image.png](https://ucc.alicdn.com/pic/developer-ecology/1fec116160d54c0ebb1b4e6b00ee958f.png)


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有